package com.fzhucc.modules.pms.service

import cn.hutool.core.lang.Snowflake
import com.alibaba.fastjson.JSONObject
import com.fzhucc.base.PageDTO
import com.fzhucc.exception.BadRequestException
import com.fzhucc.modules.fenRecordLog.service.FenRecordLogService
import com.fzhucc.modules.pms.domain.Project
import com.fzhucc.modules.pms.domain.ProjectLog
import com.fzhucc.modules.pms.domain.ProjectNotice
import com.fzhucc.modules.pms.domain.dto.ProjectDto
import com.fzhucc.modules.pms.domain.dto.ProjectMeCriteria
import com.fzhucc.modules.pms.domain.dto.ProjectMeQueryCriteria
import com.fzhucc.modules.pms.domain.dto.ProjectQueryCriteria
import com.fzhucc.modules.pms.repository.ProjectLargeSmallRepository
import com.fzhucc.modules.pms.repository.ProjectLogRepository
import com.fzhucc.modules.pms.repository.ProjectNoticeRepository
import com.fzhucc.modules.pms.repository.ProjectRepository
import com.fzhucc.modules.pms.service.mapstruct.ProjectMapper
import com.fzhucc.modules.sms.SmsService
import com.fzhucc.modules.system.domain.User
import com.fzhucc.modules.system.repository.UserRepository
import com.fzhucc.modules.system.service.UserService
import com.fzhucc.utils.*
import lombok.RequiredArgsConstructor
import org.apache.dubbo.config.annotation.DubboReference
import org.jeecg.pms.service.IPmsProjectService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.domain.Pageable
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.IOException
import java.sql.Timestamp
import java.util.*
import javax.servlet.http.HttpServletResponse

/**
 * @author Woolsen
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-11-17
 */
@Service
@RequiredArgsConstructor
class ProjectService(
    private val userService: UserService,
    private val userRepository: UserRepository,
    private val projectRepository: ProjectRepository,
    private val projectLargeSmallRepository: ProjectLargeSmallRepository,
    private val projectNoticeRepository: ProjectNoticeRepository,
    private val projectMapper: ProjectMapper,
    private val fenRecordLogService: FenRecordLogService,
    private val smsService: SmsService,
    private val projectLogRepository: ProjectLogRepository,
    private val wxClient: WxClient
) {

    @DubboReference(group = "fuzhou", timeout = 60000, check = false)
    private lateinit var fuzhouProjectService: IPmsProjectService

    @DubboReference(group = "fuqing", timeout = 60000, check = false)
    private lateinit var fuqingProjectService: IPmsProjectService

    @DubboReference(group = "test", timeout = 60000, check = false)
    private lateinit var testProjectService: IPmsProjectService

    @Value("\${org.area.all}")
    lateinit var all: String

    @Value("\${org.area.all2}")
    lateinit var all2: String

    @Value("\${fen.type.xm}")
    lateinit var xm: String


    private val snowflake = Snowflake()

    companion object {
        private val log = LoggerFactory.getLogger(ProjectService::class.java)
    }

    @Scheduled(cron = "0 0 1 * * ?")
    fun syncFromSci() {
        syncFromSci("福州三创大赛", fuzhouProjectService)
        syncFromSci("福清三创大赛", fuqingProjectService)
        syncFromSci("2022年五小项目", testProjectService)
    }

    @Transactional(rollbackFor = [Exception::class])
    fun syncFromSciWx(): String {
        try {
            var lastCount = 0;
            var count = 0
            //post请求到大赛开放接口 遍历入库
            val str = HttpUtils2.post("http://five.fzzgsc.com/api/wx/five/AllList", "")
            val jsonObject = JSONObject.parseObject(str)
            val status = jsonObject.get("code")
            if (status != 200) {
                throw BadRequestException("五小大赛数据获取失败")
            }
            val mapList = jsonObject.get("result")
            if (mapList != null) {
                val parseJsonArray = ParseJsonArray()
                val lastlist = parseJsonArray.parseJsonArray(mapList.toString())
                if (lastlist != null && lastlist.size > 0) {
                    lastCount = lastlist.size
                    lastlist.forEach { pms ->
                        val projectName = pms.projectName
                        var phone = ""
                        //查询数据库里是否有 项目名称及电话相同的情况 有则直接替换 没有新增
                        //val res = projectRepository.findByProjectNameWithPhone(projectName, phone)
                        val res = projectRepository.findByProjectNameWithSource(projectName, pms.raceName)
                        //val res = projectRepository.findByProjectName(projectName)
                        if (res != null && res.size > 0) {
                            res.forEach { resPms ->
                                projectRepository.deleteById(resPms.id)
                            }
                            val newPms = Project()
                            newPms.id = snowflake.nextIdStr()
                            newPms.projectName = projectName

                            if (pms.phone == null && pms.userAccount == null) {
                                phone = ""
                            } else
                                if (pms.phone != null && !pms.phone.equals("")) {
                                    phone = pms.phone
                                } else
                                    if (pms.phone != null && pms.phone.equals("") && pms.userAccount != null && !pms.userAccount.equals(
                                            ""
                                        )
                                    ) {
                                        phone = pms.userAccount
                                    } else
                                        if (pms.phone == null && pms.userAccount != null && !pms.userAccount.equals("")) {
                                            phone = pms.userAccount
                                        } else {
                                            phone = ""
                                        }
                            newPms.phone = phone
                            newPms.level = 1
                            newPms.stageName = pms.stageName
                            newPms.channelType = pms.channelType
                            newPms.delFlag = pms.delFlag
                            newPms.isShow = true
                            newPms.allowShow = true
                            //newPms.source = "五小发明大赛"
                            newPms.source = pms.raceName
                            //TODO 新增五小同步数据
                            newPms.details = pms.details
                            newPms.output = pms.output
                            newPms.investment = pms.investment
                            newPms.lastScore = if (pms.lastScore == null) {
                                ""
                            } else {
                                pms.lastScore.toString()
                            }
                            newPms.report = pms.report
                            newPms.firstFinisherName = pms.firstFinisherName
                            newPms.employer = pms.employer
                            newPms.awards = pms.awards
                            if (pms.awards != null && !pms.awards.equals("")) {
                                newPms.level = 2
                            }

                            newPms.contactWay = pms.contactWay
                            newPms.annualOutput = pms.annualOutput
                            newPms.contacts = pms.contacts
                            newPms.createBy = pms.createBy
                            newPms.declareSubject = pms.declareSubject
                            newPms.declareSubjectName = pms.declareSubjectName
                            newPms.description = pms.description
                            newPms.education = pms.education
                            newPms.educationalLevel = pms.educationalLevel
                            newPms.employer = pms.employer
                            newPms.firstFinisherName = pms.firstFinisherName
                            newPms.firstFinisherAddress = pms.firstFinisherAddress
                            newPms.firstFinisherPhone = pms.firstFinisherPhone
                            newPms.implementation = pms.implementation
                            newPms.intellectualProperty = pms.intellectualProperty
                            newPms.isFoundingLaborUnion = pms.isFoundingLaborUnion
                            newPms.isModelWorker = pms.isModelWorker
                            newPms.itemCategory = pms.itemCategory
                            newPms.jobTitle = pms.jobTitle
                            newPms.laborUnion = pms.laborUnion
                            newPms.lastYearRevenues = pms.lastYearRevenues
                            newPms.legalPerson = pms.legalPerson
                            newPms.mainBusiness = pms.mainBusiness
                            newPms.marketProspect = pms.marketProspect
                            newPms.modelWorker = pms.modelWorker
                            newPms.ownershipStructure = pms.ownershipStructure
                            newPms.patentForm = pms.patentForm
                            newPms.patentStatus = pms.patentStatus
                            newPms.patentApprovalTime = pms.patentApprovalTime
                            newPms.principal = pms.principal
                            newPms.principalName = pms.principalName
                            newPms.profit = pms.profit
                            newPms.projectAreaCode = pms.projectAreaCode
                            newPms.projectAreaName = pms.projectAreaName
                            newPms.projectBackground = pms.projectBackground
                            newPms.projectCode = pms.projectCode
                            newPms.projectEmployment = pms.projectEmployment
                            newPms.projectInput = pms.projectInput
                            newPms.projectVideoUrl = pms.projectVideoUrl
                            projectRepository.save(newPms)
                            count = count + 1
                        } else {
                            val newPms = Project()
                            newPms.id = snowflake.nextIdStr()
                            newPms.projectName = projectName

                            if (pms.phone == null && pms.userAccount == null) {
                                phone = ""
                            } else
                                if (pms.phone != null && !pms.phone.equals("")) {
                                    phone = pms.phone
                                } else
                                    if (pms.phone != null && pms.phone.equals("") && pms.userAccount != null && !pms.userAccount.equals(
                                            ""
                                        )
                                    ) {
                                        phone = pms.userAccount
                                    } else
                                        if (pms.phone == null && pms.userAccount != null && !pms.userAccount.equals("")) {
                                            phone = pms.userAccount
                                        } else {
                                            phone = ""
                                        }
                            newPms.phone = phone

                            newPms.level = 1
                            newPms.stageName = pms.stageName
                            newPms.channelType = pms.channelType
                            newPms.delFlag = pms.delFlag
                            newPms.isShow = true
                            newPms.allowShow = true
                            //newPms.source = "五小发明大赛"
                            newPms.source = pms.raceName
                            //TODO 新增五小同步数据
                            newPms.details = pms.details
                            newPms.output = pms.output
                            newPms.investment = pms.investment
                            newPms.lastScore = if (pms.lastScore == null) {
                                ""
                            } else {
                                pms.lastScore.toString()
                            }
                            newPms.report = pms.report
                            newPms.firstFinisherName = pms.firstFinisherName
                            newPms.employer = pms.employer
                            newPms.awards = pms.awards
                            if (pms.awards != null && !pms.awards.equals("")) {
                                newPms.level = 2
                            }

                            newPms.contactWay = pms.contactWay
                            newPms.annualOutput = pms.annualOutput
                            newPms.contacts = pms.contacts
                            newPms.createBy = pms.createBy
                            newPms.declareSubject = pms.declareSubject
                            newPms.declareSubjectName = pms.declareSubjectName
                            newPms.description = pms.description
                            newPms.education = pms.education
                            newPms.educationalLevel = pms.educationalLevel
                            newPms.employer = pms.employer
                            newPms.firstFinisherName = pms.firstFinisherName
                            newPms.firstFinisherAddress = pms.firstFinisherAddress
                            newPms.firstFinisherPhone = pms.firstFinisherPhone
                            newPms.implementation = pms.implementation
                            newPms.intellectualProperty = pms.intellectualProperty
                            newPms.isFoundingLaborUnion = pms.isFoundingLaborUnion
                            newPms.isModelWorker = pms.isModelWorker
                            newPms.itemCategory = pms.itemCategory
                            newPms.jobTitle = pms.jobTitle
                            newPms.laborUnion = pms.laborUnion
                            newPms.lastYearRevenues = pms.lastYearRevenues
                            newPms.legalPerson = pms.legalPerson
                            newPms.mainBusiness = pms.mainBusiness
                            newPms.marketProspect = pms.marketProspect
                            newPms.modelWorker = pms.modelWorker
                            newPms.ownershipStructure = pms.ownershipStructure
                            newPms.patentForm = pms.patentForm
                            newPms.patentStatus = pms.patentStatus
                            newPms.patentApprovalTime = pms.patentApprovalTime
                            newPms.principal = pms.principal
                            newPms.principalName = pms.principalName
                            newPms.profit = pms.profit
                            newPms.projectAreaCode = pms.projectAreaCode
                            newPms.projectAreaName = pms.projectAreaName
                            newPms.projectBackground = pms.projectBackground
                            newPms.projectCode = pms.projectCode
                            newPms.projectEmployment = pms.projectEmployment
                            newPms.projectInput = pms.projectInput
                            newPms.projectVideoUrl = pms.projectVideoUrl
                            projectRepository.save(newPms)
                            count = count + 1
                        }
                    }
                }
            }
            val res = "拉取五小发明大赛项目成功，拉取${lastCount}个项目，同步${count}个项目"
            log.info(res)
            return res
        } catch (e: Exception) {
            log.error("拉取五小发明大赛项目失败", e.cause)
            return "拉取五小发明大赛项目失败"
        }
    }


    private fun syncFromSci(source: String, service: IPmsProjectService) {
        try {
            val projects = service.allProjects
            var count = 0
            projects.forEach { project ->
                val id = "${source.hashCode()}-${project.id}"
                val alreadyEdit = projectRepository.findAlreadyEditById(id)
                if (project.projectName == null || (alreadyEdit != null && alreadyEdit)) {
                    // 检查是否编辑过，若编辑过，则不覆盖
                } else {
                    if (alreadyEdit != null) {
                        projectRepository.deleteById(id)
                    }
                    val entity = projectMapper.toEntity(project).apply {
                        this.id = id
                        this.level = 1
                        this.alreadyEdit = false
                        this.source = source
                    }
                    projectRepository.save(entity)
                    count++
                }
            }
            log.info("拉取[${source}]项目成功，拉取${projects.size}个项目，同步${count}个项目")
        } catch (e: Exception) {
            log.error("拉取[${source}]项目失败", e.cause)
        }
    }


    fun queryWxMe(criteria: ProjectMeCriteria, pageable: Pageable): PageDTO<ProjectDto> {
        /*criteria.delFlag = "0"
        criteria.userId = SecurityUtils.getCurrentUserId()
        val page = projectRepository.findAll({ root, _, criteriaBuilder ->
            QueryHelp.getPredicate(root, criteria, criteriaBuilder)
        }, pageable)
        return PageDTO.by(page.map { projectMapper.toDto(it) })*/
        val userId = SecurityUtils.getCurrentUserId();
        val res = userRepository.findById(userId)
        if (!res.isPresent) {
            throw BadRequestException("用户未登录")
        }
        if (criteria.projectType == null) {
            throw BadRequestException("请选择分类类型")
        }
        val user = res.get()
        var flag = false
        if (criteria.projectName != null && !criteria.projectName.equals("")) {
            flag = true
        }
        if (user.phone != null && user.phone != "") {
            if (criteria.projectType == 0) {//全选
                if (flag) {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeAllLikeName(
                            userId,
                            user.phone,
                            user.orgArea,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeAllLikeNameO(
                            userId,
                            user.phone,
                            user.orgArea,
                            criteria.projectName,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                } else {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeAll(userId, user.phone, pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeAllO(userId, user.phone, user.orgArea, pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                }
            } else if (criteria.projectType == 1) {//科创
                if (flag) {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeAllKcLikeName(
                            userId,
                            user.phone,
                            "%" + "五小" + "%",
                            criteria.projectName,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeAllKcLikeNameO(
                            userId,
                            user.phone,
                            "%" + "五小" + "%",
                            criteria.projectName,
                            user.orgArea,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                } else {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page =
                            projectRepository.findMeAllKc(userId, user.phone, "%" + "五小" + "%", pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page =
                            projectRepository.findMeAllKcO(
                                userId,
                                user.phone,
                                "%" + "五小" + "%",
                                user.orgArea,
                                pageable
                            )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                }
            } else if (criteria.projectType == 2) {//五小
                if (flag) {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeAllWxLikeName(
                            userId,
                            user.phone,
                            "%" + "五小" + "%",
                            criteria.projectName,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeAllWxLikeNameO(
                            userId,
                            user.phone,
                            "%" + "五小" + "%",
                            criteria.projectName,
                            user.orgArea,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                } else {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page =
                            projectRepository.findMeAllWx(userId, user.phone, "%" + "五小" + "%", pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page =
                            projectRepository.findMeAllWxO(
                                userId,
                                user.phone,
                                "%" + "五小" + "%",
                                user.orgArea,
                                pageable
                            )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                }
            } else {
                if (flag) {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeAllLikeName(
                            userId,
                            user.phone,
                            criteria.projectName,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeAllLikeNameO(
                            userId,
                            user.phone,
                            user.orgArea,
                            criteria.projectName,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                } else {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeAll(userId, user.phone, pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeAllO(userId, user.phone, user.orgArea, pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                }
            }
        } else {
            if (criteria.projectType == 0) {//全选
                if (flag) {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeWithOutPhoneAllLikeName(
                            userId,
                            criteria.projectName,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeWithOutPhoneAllLikeNameO(
                            userId,
                            criteria.projectName,
                            user.orgArea,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                } else {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeWithOutPhoneAll(userId, pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeWithOutPhoneAllO(userId, user.orgArea, pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                }
            } else if (criteria.projectType == 1) {//科创
                if (flag) {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeWithOutPhoneAllKcLikeName(
                            userId,
                            "%" + "五小" + "%",
                            criteria.projectName,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeWithOutPhoneAllKcLikeNameO(
                            userId,
                            "%" + "五小" + "%",
                            criteria.projectName,
                            user.orgArea,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                } else {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page =
                            projectRepository.findMeWithOutPhoneAllKc(userId, "%" + "五小" + "%", pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page =
                            projectRepository.findMeWithOutPhoneAllKcO(
                                userId,
                                "%" + "五小" + "%",
                                user.orgArea,
                                pageable
                            )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                }
            } else if (criteria.projectType == 2) {//五小
                if (flag) {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeWithOutPhoneAllWxLikeName(
                            userId,
                            "%" + "五小" + "%",
                            criteria.projectName,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeWithOutPhoneAllWxLikeNameO(
                            userId,
                            "%" + "五小" + "%",
                            criteria.projectName,
                            user.orgArea,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                } else {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page =
                            projectRepository.findMeWithOutPhoneAllWx(userId, "%" + "五小" + "%", pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page =
                            projectRepository.findMeWithOutPhoneAllWxO(
                                userId,
                                "%" + "五小" + "%",
                                user.orgArea,
                                pageable
                            )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                }
            } else {
                if (flag) {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeWithOutPhoneAllLikeName(
                            userId,
                            criteria.projectName,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeWithOutPhoneAllLikeNameO(
                            userId,
                            criteria.projectName,
                            user.orgArea,
                            pageable
                        )
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                } else {
                    if ((user.orgArea != null && user.orgArea == all) || user.orgArea == null) {
                        //TODO
                        val page = projectRepository.findMeWithOutPhoneAll(userId, pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    } else {
                        val page = projectRepository.findMeWithOutPhoneAllO(userId, user.orgArea, pageable)
                        return PageDTO.by(page.map { projectMapper.toDto(it) })
                    }
                }
            }
        }
    }


    //根据不同设置不同的部门查看
    /*fun  setCriteria(criteria :ProjectMeQueryCriteria) {
        val userId = SecurityUtils.getCurrentUserId()
        if (userId == null) {//未登录则外面传进来
            val orgArea = criteria.getOrgArea()
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                criteria.orgArea = null
            }
        } else {
            val userOptional = userRepository.findById(userId)
            val res = userOptional.get()
            if (res.getOrgArea() != null && res.getOrgArea().equals(all)) {//用的org组织最高看全部
                criteria.orgArea = null
            } else {
                criteria.orgArea = res.getOrgArea()//如果用户的权限不是福建省则 只能看到对应的组织
            }
        }
    }*/

    //根据不同设置不同的部门查看
    fun setCriteria(criteria: ProjectMeQueryCriteria): String {
        var userId: Long? = null
        try {
            userId = SecurityUtils.getCurrentUserId()
        } catch (e: Exception) {
            //throw new RuntimeException(e)
            val orgArea = criteria.getOrgArea()
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return ""
            } else {
                return orgArea
            }
        }
        if (userId != null) {
            val res = userRepository.findById(userId)
            if (res.get().getOrgArea() != null && (res.get().getOrgArea().equals(all) || res.get().getOrgArea().equals(all2))) {//用的org组织最高看全部
                return ""
            } else {
                //return res.get().getOrgArea()//如果用户的权限不是福建省则 只能看到对应的组织
                if (res.get().getOrgArea() == null || res.get().getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return ""
                }
                if (res.get().getOrgArea().contains(";")) {
                    val split = res.get().getOrgArea().split(";")
                    if (split.size == 2) {
                        return split[1]
                    } else if (split.size == 3) {
                        return split[2]
                    } else if (split.size == 1) {
                        return split[0]
                    } else {
                        throw BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw BadRequestException("用户ID未找到")
        }
    }

    //根据不同设置不同的部门查看
    /*fun setCriteriaProjectQueryCriteria(criteria: ProjectQueryCriteria) {
        val userId = SecurityUtils.getCurrentUserId()
        if (userId == null) {//未登录则外面传进来
            val orgArea = criteria.getOrgArea()
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                criteria.orgArea = null
            }
        } else {
            val userOptional = userRepository.findById(userId)
            val res = userOptional.get()
            if (res.getOrgArea() != null && res.getOrgArea().equals(all)) {//用的org组织最高看全部
                criteria.orgArea = null
            } else {
                criteria.orgArea = res.getOrgArea()//如果用户的权限不是福建省则 只能看到对应的组织
            }
        }
    }*/

    //根据不同设置不同的部门查看
    fun setCriteriaProjectQueryCriteria(criteria: ProjectQueryCriteria): String {
        var userId: Long? = null
        try {
            userId = SecurityUtils.getCurrentUserId()
        } catch (e: Exception) {
            //throw new RuntimeException(e);
            val orgArea = criteria.orgArea
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return ""
            }
        }
        if (userId != null) {
            val res = userRepository.findById(userId)
            if (res.get().getOrgArea() != null && (res.get().getOrgArea().equals(all) || res.get().getOrgArea().equals(all2))) {//用的org组织最高看全部
                return ""
            } else {
                //return res.get().getOrgArea()//如果用户的权限不是福建省则 只能看到对应的组织
                if (res.get().getOrgArea() == null || res.get().getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return ""
                }
                if (res.get().getOrgArea().contains(";")) {
                    val split = res.get().getOrgArea().split(";")
                    if (split.size == 2) {
                        return split[1]
                    } else if (split.size == 3) {
                        return split[2]
                    } else if (split.size == 1) {
                        return split[0]
                    } else {
                        throw BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw BadRequestException("用户ID未找到")
        }
    }

    fun orgAreaReturn(): String {
        val userId = SecurityUtils.getCurrentUserId()
        if (userId == null) {//未登录则外面传进来
            return ""
        } else {
            val userOptional = userRepository.findById(userId)
            val res = userOptional.get()
            if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                //不赋予则返回所有都能看
                return ""
            }
            if (res.getOrgArea().contains(";")) {
                val split = res.getOrgArea().split(";")
                if (split.size == 2) {
                    return split[1]
                } else if (split.size == 3) {
                    return split[1]
                } else if (split.size == 1) {
                    return split[0]
                } else {
                    throw BadRequestException("未符合规范的地区区域");
                }
            } else {
                throw BadRequestException("未符合规范的地区区域");
            }
        }
    }

    fun queryMe(criteria: ProjectMeQueryCriteria, pageable: Pageable): PageDTO<ProjectDto> {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.orgArea = null
            }
        } else {
            val criteria1 = setCriteria(criteria)
            if (criteria1 == "") {
                criteria.orgArea = null
            } else {
                criteria.orgArea = criteria1
            }
        }

        criteria.delFlag = "0"
        criteria.userId = SecurityUtils.getCurrentUserId()
        val page = projectRepository.findAll({ root, _, criteriaBuilder ->
            QueryHelp.getPredicate(root, criteria, criteriaBuilder)
        }, pageable)
        return PageDTO.by(page.map { projectMapper.toDto(it) })
    }

    fun queryAll(criteria: ProjectQueryCriteria, pageable: Pageable): Map<String, Any> {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(xm)
        } catch (e: Exception) {

        }
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.orgArea = null
            }
        } else {
            //管理端根据登录用户地区
            val criteria1 = setCriteriaProjectQueryCriteria(criteria)
            if (criteria1 == "") {
                criteria.orgArea = null
            } else {
                criteria.orgArea = criteria1
            }
        }

        val page = projectRepository.findAll({ root, _, criteriaBuilder ->
            QueryHelp.getPredicate(root, criteria, criteriaBuilder)
        }, pageable)
        return PageUtil.toPage(page.map { projectMapper.toDto(it) })
    }

    fun queryAllWithOutDetails(criteria: ProjectQueryCriteria, pageable: Pageable): Map<String, Any> {
        val page = projectLargeSmallRepository.queryAllProNameWithOutDetails(criteria.level, pageable)
        return PageUtil.toPage(page)
    }

    fun queryAllWithOutDetailsByOrgArea(criteria: ProjectQueryCriteria, pageable: Pageable): Map<String, Any> {
        val page = projectLargeSmallRepository.queryAllProNameWithOutDetailsByOrgArea(
            criteria.level,
            criteria.orgArea,
            pageable
        )
        return PageUtil.toPage(page)
    }

    fun queryAll(criteria: ProjectQueryCriteria): List<ProjectDto> {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.orgArea = null
            }
        } else {
            val criteria1 = setCriteriaProjectQueryCriteria(criteria)
            if (criteria1 == "") {
                criteria.orgArea = null
            } else {
                criteria.orgArea = criteria1
            }
        }
        return projectMapper.toDto(projectRepository.findAll { root, _, criteriaBuilder ->
            QueryHelp.getPredicate(root, criteria, criteriaBuilder)
        })
    }

    fun queryAllNormal(): List<ProjectDto> {
        return projectMapper.toDto(projectRepository.findAllByNormalStatus())
        //Thread.sleep(110000)
    }


    fun queryByLevel(level: Int): Int {
        //职创项目库  = 优秀项目库  + 重点项目库 + 职创项目库
        //优秀项目库 =  优秀项目库 + 重点项目
        //重点项目
        if (level == 1) {//职创项目库
            val level1 = projectRepository.queryByLevel(1)
            val level2 = projectRepository.queryByLevel(2)
            val level3 = projectRepository.queryByLevel(3)
            return level1 + level2 + level3
        } else if (level == 2) {//优秀项目库
            val level2 = projectRepository.queryByLevel(2)
            val level3 = projectRepository.queryByLevel(3)
            return level2 + level3
        } else if (level == 3) {//优秀项目库
            val level3 = projectRepository.queryByLevel(3)
            return level3
        } else {
            return 0
        }
    }

    fun queryByLevelByOrgCode(level: Int, orgArea: String): Int {
        //职创项目库  = 优秀项目库  + 重点项目库 + 职创项目库
        //优秀项目库 =  优秀项目库 + 重点项目
        if ((orgArea != null && orgArea == all) || orgArea == null) {
            //重点项目
            if (level == 1) {//职创项目库
                val level1 = projectRepository.queryByLevelOrgArea(1)
                val level2 = projectRepository.queryByLevelOrgArea(2)
                val level3 = projectRepository.queryByLevelOrgArea(3)
                return level1 + level2 + level3
            } else if (level == 2) {//优秀项目库
                val level2 = projectRepository.queryByLevelOrgArea(2)
                val level3 = projectRepository.queryByLevelOrgArea(3)
                return level2 + level3
            } else if (level == 3) {//优秀项目库
                val level3 = projectRepository.queryByLevelOrgArea(3)
                return level3
            } else {
                return 0
            }
        } else {
            //重点项目
            if (level == 1) {//职创项目库
                val level1 = projectRepository.queryByLevelOrgAreaO(1, orgArea)
                val level2 = projectRepository.queryByLevelOrgAreaO(2, orgArea)
                val level3 = projectRepository.queryByLevelOrgAreaO(3, orgArea)
                return level1 + level2 + level3
            } else if (level == 2) {//优秀项目库
                val level2 = projectRepository.queryByLevelOrgAreaO(2, orgArea)
                val level3 = projectRepository.queryByLevelOrgAreaO(3, orgArea)
                return level2 + level3
            } else if (level == 3) {//优秀项目库
                val level3 = projectRepository.queryByLevelOrgAreaO(3, orgArea)
                return level3
            } else {
                return 0
            }
        }
    }

    fun findById(id: String): ProjectDto {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(xm)
        } catch (e: Exception) {

        }

        val project = projectRepository.findById(id).orElseGet { Project() }
        ValidationUtil.isNull(project.id, "Project", "id", id)
        //查询热度 +1
        val hot = project.hot
        project.hot = (hot + 1)
        val save = projectRepository.save(project)
        return projectMapper.toDto(save)
    }

    @Transactional(rollbackFor = [Exception::class])
    fun create(resources: ProjectDto, hasPremission: Boolean): ProjectDto {
        val currentUserId = JwtSecurityUtils.getCurrentUserId()
        val project = projectMapper.toEntity(resources)
        project.id = snowflake.nextIdStr()
        project.alreadyEdit = true
        project.user = User(currentUserId)
        project.allowShow = project.allowShow ?: true
        if (!project.allowShow) {
            project.isShow = false
        }
        if (!hasPremission) {
            project.isShow = false
            project.status = Project.STATUS_ING
        }
        project.delFlag = "0"
        //判断五个条件是否有一个满足 满足则设置为自动通过  并直接进入项目库不需要审核
        if (project.isEmergingAreas || project.isCoreTechnology || project.isInnovationPlanning || project.isModelWorkerJoin || project.isUniversityStudentUndertaking) {
            project.isAutoPass = true
            //project.allowShow = true
            project.isShow = true
            project.status = Project.STATUS_PASS

            if (project.contactWay != null && project.contactWay != "") {
                val phoneArray = arrayOf(project.contactWay)//项目联系电话
                smsService.SendSmsAutoApproved(phoneArray, project.projectName)//自动审核发送短信
            } else if (project.phone != null && project.phone != "") {
                val phoneArray = arrayOf(project.phone)//项目联系电话
                smsService.SendSmsAutoApproved(phoneArray, project.phone)//自动审核发送短信
            }
        } else {
            project.isAutoPass = false

            if (project.contactWay != null && project.contactWay != "") {
                val phoneArray = arrayOf(project.contactWay)//项目联系电话
                smsService.SendSmsIntoProject(phoneArray, project.projectName)//进入项目库发送短信
            } else if (project.phone != null && project.phone != "") {
                val phoneArray = arrayOf(project.phone)//项目联系电话
                smsService.SendSmsIntoProject(phoneArray, project.phone)//进入项目库发送短信
            }
        }
        project.orgArea = orgAreaReturn()
        project.hot = 0
        val projectResult = projectRepository.save(project)
        recordProjectLog(projectResult.id, projectResult.level, 0)
        return projectMapper.toDto(projectResult)
    }

    @Transactional(rollbackFor = [Exception::class])
    fun createBeReviewed(resources: ProjectDto, isAdmin: Boolean): ProjectDto {
        val currentUserId = JwtSecurityUtils.getCurrentUserId()
        val project = projectMapper.toEntity(resources)
        project.id = snowflake.nextIdStr()
        project.alreadyEdit = true
        project.user = User(currentUserId)
        project.allowShow = project.allowShow ?: true
        if (!project.allowShow) {
            project.isShow = false
        }
        resources.isShow = false
        resources.status = Project.STATUS_ING
        project.delFlag = "0"
        project.orgArea = orgAreaReturn()
        val projectResult = projectRepository.save(project)
        recordProjectLog(projectResult.id, projectResult.level, 0)
        return projectMapper.toDto(projectResult)
    }

    @Transactional
    fun recordProjectLog(project_id: String, afterlevel: Int, beforelevel: Int) {
        if (beforelevel == 0) {//新增
            val projectLog = ProjectLog()
            projectLog.projectId = project_id
            projectLog.afterLevel = afterlevel
            projectLog.beforeLevel = 0
            projectLog.changeTime = Timestamp(Date().time)
            var str = ""
            if (afterlevel == 1) {
                str = "职创项目"
            }
            if (afterlevel == 2) {
                str = "优秀项目"
            }
            if (afterlevel == 3) {
                str = "重点项目"
            }
            projectLog.describe = "项目进入$str"
            projectLogRepository.save(projectLog)
        } else {//编辑
            val projectLog = ProjectLog()
            projectLog.projectId = project_id
            projectLog.afterLevel = afterlevel
            projectLog.beforeLevel = beforelevel
            projectLog.changeTime = Timestamp(Date().time)
            var strBefore = ""
            var strAfter = ""
            if (afterlevel == 1) {
                strAfter = "职创项目"
            }
            if (afterlevel == 2) {
                strAfter = "优秀项目"
            }
            if (afterlevel == 3) {
                strAfter = "重点项目"
            }
            if (beforelevel == 1) {
                strBefore = "职创项目"
            }
            if (beforelevel == 2) {
                strBefore = "优秀项目"
            }
            if (beforelevel == 3) {
                strBefore = "重点项目"
            }
            projectLog.describe = "项目从" + strBefore + "进入" + strAfter
            projectLogRepository.save(projectLog)
        }
    }

    @Transactional
    fun recordProjectNotice(user_id: Long, project_id: String, level: Int, auditStr: String, auditStatus: Int) {
        val projectNotice = ProjectNotice()
        projectNotice.userId = user_id
        projectNotice.project = Project().apply {
            this.id = project_id
        }
        projectNotice.happenTime = Timestamp(Date().time)
        //projectNotice.isShow = 1
        var str = ""
        if (level == 1) {
            str = "职创项目"
        }
        if (level == 2) {
            str = "优秀项目"
        }
        if (level == 3) {
            str = "重点项目"
        }
        projectNotice.msg = "$auditStr,项目进入$str"
        projectNotice.currentLevel = level
        projectNotice.auditStatus = auditStatus
        projectNoticeRepository.save(projectNotice)
    }

    @Transactional
    fun recordProjectNoticeChangeLevel(
        user_id: Long,
        project_id: String,
        level: Int,
        oldLevelStr: String,
        newLevelStr: String,
        auditStatus: Int
    ) {
        val projectNotice = ProjectNotice()
        projectNotice.userId = user_id
        projectNotice.project = Project().apply {
            this.id = project_id
        }
        projectNotice.happenTime = Timestamp(Date().time)
        projectNotice.msg = "项目等级变更由" + oldLevelStr + "进入" + newLevelStr
        projectNotice.currentLevel = level
        projectNotice.auditStatus = auditStatus
        projectNoticeRepository.save(projectNotice)
    }

    @Transactional(rollbackFor = [Exception::class])
    fun update(resources: Project, isAdmin: Boolean): ProjectDto {
        val userId = SecurityUtils.getCurrentUserId()
        var project = projectRepository.findById(resources.id).orElseGet { Project() }
        if (!isAdmin && userId != project.userId) {
            throw BadRequestException("非法操作")
        }
        ValidationUtil.isNull(project, "Project", "id", resources.id)

        var flag = ""
        var oldLevel = 0
        var newLevel = 0

        val previousLevel = project.level
        val previousstatus = project.status
        project.copy(resources)
        if (previousLevel != project.level) {
            //变更项目等级
            flag = "changeLevel"
            oldLevel = previousLevel
            newLevel = project.level
        }
        if (previousstatus != 1 && project.status == 1) {
            //审核通过的情况
            flag = "pass"
        }
        if (previousstatus != -1 && project.status == -1) {
            //审核拒绝的情况
            flag = "fail"
        }

        project.alreadyEdit = true
        if (!project.allowShow) {
            project.isShow = false
        }
        project.orgArea = orgAreaReturn()
        project = projectRepository.save(project)
        if (project.user != null) {
            val user = project.user
            val UserRes = userService.findById(user.id)
            log.info(UserRes.phone)
            val phoneArray = arrayOf(UserRes.phone)

            if (project.status == Project.STATUS_PASS) {
                userService.updateProjectLevel(user.id, project.level)
            } else {
                //审核拒绝
                val maxProjectLevel = projectRepository.findMaxLevelByUserId(user.id)
                userService.updateProjectLevel(user.id, maxProjectLevel)
            }
            if (flag.equals("pass")) {
                recordProjectNotice(user.id, project.id, project.level, "审核通过", 1)
                //发短信
                if (project.level == 1) {
                    smsService.SendSmsWithIntoProjectLibrary(phoneArray, project.projectName)
                }
                if (project.level == 2) {
                    smsService.SendSmsWithIntoExcellentProjectLibrary(phoneArray, project.projectName)
                }
                if (project.level == 3) {
                    smsService.SendSmsWithIntoKeyProjectLibrary(phoneArray, project.projectName)
                }
            }
            if (flag.equals("fail")) {
                recordProjectNotice(user.id, project.id, project.level, "审核拒绝", 0)
                smsService.SendSmsIntoLibraryPassFail(phoneArray, project.projectName)
            }
            if (flag.equals("changeLevel")) {
                var oldLevelStr = ""
                var newLevelStr = ""
                if (oldLevel == 1) {
                    oldLevelStr = "职创项目"
                }
                if (newLevel == 1) {
                    newLevelStr = "职创项目"
                }
                if (oldLevel == 2) {
                    oldLevelStr = "优秀项目"
                }
                if (newLevel == 2) {
                    newLevelStr = "优秀项目"
                }
                if (oldLevel == 3) {
                    oldLevelStr = "重点项目"
                }
                if (newLevel == 3) {
                    newLevelStr = "重点项目"
                }
                recordProjectNoticeChangeLevel(user.id, project.id, project.level, oldLevelStr, newLevelStr, 1)
                recordProjectLog(project.id, newLevel, oldLevel)
                smsService.SendSmsIntoLibraryChangeLevel(
                    phoneArray,
                    project.projectName,
                    oldLevelStr,
                    newLevelStr
                )
            }
        }
        return projectMapper.toDto(project)
    }

    fun deleteAll(ids: Array<String>) {
        for (id in ids) {
            if (JwtSecurityUtils.hasAuthority("project:del")) {
                //projectRepository.deleteById(id)
                //设置删除状态为1
                val res = projectRepository.findById(id)
                if (!res.isPresent) {
                    throw BadRequestException("项目未找到");
                }
                val project = res.get()
                project.delFlag = "1"
                val currentTimestamp =  Timestamp(System.currentTimeMillis())
                project.deleteTime = currentTimestamp
                projectRepository.save(project)
            } else {
                val res = projectRepository.findById(id)
                if (res.isPresent) {
                    val project = res.get()
                    val userId = SecurityUtils.getCurrentUserId() ?: throw BadRequestException("登录用户ID未找到")
                    if (project.userId == null) {
                        throw BadRequestException("项目库用户ID未找到")
                    }
                    if (userId != project.userId) {
                        throw BadRequestException("只允许删除个人项目")
                    }
                    //projectRepository.deleteById(id)
                    project.delFlag = "1"
                    val currentTimestamp =  Timestamp(System.currentTimeMillis())
                    project.deleteTime = currentTimestamp
                    projectRepository.save(project)
                }
            }
        }
    }

    @Throws(IOException::class)
    fun download(all: List<ProjectDto>, response: HttpServletResponse) {
        val list: MutableList<Map<String, Any>> = ArrayList()
        for (project in all) {
            val map: MutableMap<String, Any> = LinkedHashMap()
            map["赛事名称"] = if (project.raceName == null) "" else project.raceName
            map["赛事编号"] = if (project.raceCode == null) "" else project.raceCode
            map["赛事级别（字典）"] = if (project.raceRank == null) "" else project.raceRank
            map["渠道类型 1大赛 2项目申报"] = if (project.channelType == null) "" else project.channelType
            map["参数人员名称"] = if (project.userName == null) "" else project.userName
            map["参数人员账号"] = if (project.userAccount == null) "" else project.userAccount
            map["项目编码"] = if (project.projectCode == null) "" else project.projectCode
            map["项目名称"] = if (project.projectName == null) "" else project.projectName
            map["项目所在地编码"] = if (project.projectAreaCode == null) "" else project.projectAreaCode
            map["项目所在地名称"] = if (project.projectAreaName == null) "" else project.projectAreaName
            map["赛区"] = if (project.raceArea == null) "" else project.raceArea
            map["所属赛道（字典）"] = if (project.raceTrack == null) "" else project.raceTrack
            map["所属领域"] = if (project.raceDomain == null) "" else project.raceDomain
            map["申报企业"] = if (project.companyName == null) "" else project.companyName
            map["注册地址"] = if (project.companyAddress == null) "" else project.companyAddress
            map["注册时间"] = if (project.registrationTime == null) "" else project.registrationTime
            map["主营业务"] = if (project.mainBusiness == null) "" else project.mainBusiness
            map["注册资本"] = if (project.registeredCapital == null) "" else project.registeredCapital
            map["营业执照 统一社会信用代码"] = if (project.businessLicense == null) "" else project.businessLicense
            map["法人代表"] = if (project.legalPerson == null) "" else project.legalPerson
            map["学历"] = if (project.education == null) "" else project.education
            map["公司就业人数"] = if (project.companyPeopleNum == null) "" else project.companyPeopleNum
            map["上年经营收入"] = if (project.lastYearRevenues == null) "" else project.lastYearRevenues
            map["若无成立工会 是否承诺在大赛决赛日后三个月内成立工会组织"] =
                if (project.isFoundingLaborUnion == null) "" else project.isFoundingLaborUnion
            map["企业股权结构情况"] = if (project.ownershipStructure == null) "" else project.ownershipStructure
            map["申报项目主体"] = if (project.declareSubject == null) "" else project.declareSubject
            map["地址"] = if (project.address == null) "" else project.address
            map["负责人"] = if (project.principal == null) "" else project.principal
            map["项目就业人数"] = if (project.projectEmployment == null) "" else project.projectEmployment
            map["所属工会（如有）"] = if (project.laborUnion == null) "" else project.laborUnion
            map["核心知识产权数量及情况说明"] =
                if (project.intellectualProperty == null) "" else project.intellectualProperty
            map["项目背景"] = if (project.projectBackground == null) "" else project.projectBackground
            map["产品说明"] = if (project.description == null) "" else project.description
            map["市场前景"] = if (project.marketProspect == null) "" else project.marketProspect
            map["推荐渠道"] = if (project.recommendChannels == null) "" else project.recommendChannels
            map["项目图"] = if (project.projectImgUrl == null) "" else project.projectImgUrl
            map["项目视频"] = if (project.projectVideoUrl == null) "" else project.projectVideoUrl
            map["是否劳模"] = if (project.isModelWorker == null) "" else project.isModelWorker
            map["联系人"] = if (project.contacts == null) "" else project.contacts
            map["联系方式"] = if (project.contactWay == null) "" else project.contactWay
            map["通讯地址"] = if (project.contactAddress == null) "" else project.contactAddress
            map["联系电话"] = if (project.phone == null) "" else project.phone
            map["当前阶段名称"] = if (project.stageName == null) "" else project.stageName
            map["当前阶段级别"] = if (project.stageGrade == null) "" else project.stageGrade
            map["状态 -2草稿 -1驳回 0待审核 1评比/审核中 2未晋级 3晋级/审核成功"] =
                if (project.status == null) "" else project.status
            map["项目类别"] = if (project.itemCategory == null) "" else project.itemCategory
            map["专利形式"] = if (project.patentForm == null) "" else project.patentForm
            map["专利状况"] = if (project.patentStatus == null) "" else project.patentStatus
            map["专利批准时间"] = if (project.patentApprovalTime == null) "" else project.patentApprovalTime
            map["实施方式"] = if (project.implementation == null) "" else project.implementation
            map["项目投入"] = if (project.projectInput == null) "" else project.projectInput
            map["年产值"] = if (project.annualOutput == null) "" else project.annualOutput
            map["利润"] = if (project.profit == null) "" else project.profit
            map["第一完成人姓名"] = if (project.firstFinisherName == null) "" else project.firstFinisherName
            map["性别"] = if (project.sex == null) "" else project.sex
            map["岗位职务"] = if (project.jobTitle == null) "" else project.jobTitle
            map["文化程度"] = if (project.educationalLevel == null) "" else project.educationalLevel
            map["是否允许编辑 1是 0否"] = if (project.allowEditing == null) "" else project.allowEditing
            map["工作单位"] = if (project.employer == null) "" else project.employer
            map["邮政编码"] = if (project.zipCode == null) "" else project.zipCode
            map["删除状态(0正常 1删除)"] = if (project.delFlag == null) "" else project.delFlag
            map["创建人"] = if (project.createBy == null) "" else project.createBy
            map["创建时间"] = if (project.createTime == null) "" else project.createTime
            map["更新人"] = if (project.updateBy == null) "" else project.updateBy
            map["更新时间"] = if (project.updateTime == null) "" else project.updateTime
            map["第一完成人联系电话"] = if (project.firstFinisherPhone == null) "" else project.firstFinisherPhone
            map["第一完成人地址"] = if (project.firstFinisherAddress == null) "" else project.firstFinisherAddress
            map["项目简介"] = if (project.details == null) "" else Html2Text.getContent(project.details)
            map[" canRate"] = if (project.canRate == null) "" else project.canRate
            map[" declareSubjectName"] = if (project.declareSubjectName == null) "" else project.declareSubjectName
            map["结束时间"] = if (project.endTime == null) "" else project.endTime
            map["项目等级 1-职创项目库 2-优秀项目库 3-重点项目库"] = if (project.level == null) "" else project.level
            map[" listStatus"] = if (project.listStatus == null) "" else project.listStatus
            map[" modelWorker"] = if (project.modelWorker == null) "" else project.modelWorker
            map[" principalName"] = if (project.principalName == null) "" else project.principalName
            map["备注"] = if (project.remark == null) "" else project.remark
            map["score"] = if (project.score == null) "" else project.score
            map["来源"] = if (project.source == null) "" else project.source
            map["开始时间"] = if (project.startTime == null) "" else project.startTime
            map["是否允许展示 由用户填写，用于判断后台是否能配置展示 1是 0否"] =
                if (project.allowShow == null) "" else project.allowShow
            map["是否属于以下新兴领域:《国家重点支持的高新技术领域》、《战略新兴产业分类》? 1是 0否"] =
                if (project.isEmergingAreas == null) "" else project.isEmergingAreas
            map["是否具有核心技术:已申请/授权（拥有)专利、软件著作权、集成电路布图设计权、植物新品种、新药证书、农作物品种、中药保护品种? 1是 0否"] =
                if (project.isCoreTechnology == null) "" else project.isCoreTechnology
            map["是否具有创新规划?具有创新规划、有商业计划书、项目可行性报告等? 1是 0否"] =
                if (project.isInnovationPlanning == null) "" else project.isInnovationPlanning
            map["是否有劳模工匠参与? 1是 0否"] =
                if (project.isModelWorkerJoin == null) "" else project.isModelWorkerJoin
            map["是否属于大学生创业项目? 1是 0否"] =
                if (project.isUniversityStudentUndertaking == null) "" else project.isUniversityStudentUndertaking
            map["是否自动审核通过? 1是 0否"] = if (project.isAutoPass == null) "" else project.isAutoPass
            map["是否展示? 1是 0否"] = if (project.isShow == null) "" else project.isShow
            map["排序"] = if (project.sort == null) "" else project.sort
            map["区域划分"] = if (project.orgArea == null) "" else project.orgArea
            map["知识产权附件url"] = if (project.intellectualFileUrl == null) "" else project.intellectualFileUrl
            map["热度"] = if (project.hot == null) "" else project.hot
            list.add(map)
        }
        FileUtil.downloadExcel(list, response)
    }

    fun getQRcode(id: String): String {
        val res = projectRepository.findById(id)
        if (!res.isPresent) {
            throw BadRequestException("项目库未找到")
        }
        //二维码生成
        val str = wxClient.generateMpQr("subPages/projectStore/sub/projectDetail", id)
        return str.replace("\"", "")
    }
}